package com.jkt.rms.commons.configuration;

import java.util.Iterator;
import java.util.List;

import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.intercept.web.AbstractFilterInvocationDefinitionSource;
import org.apache.log4j.Logger;

import com.jkt.rms.businessservice.UIModuleLinkupBusinessService;
import com.jkt.rms.commons.utils.ExceptionFactory;
import com.jkt.rms.commons.utils.ServiceLocator;

public class RMSDBFilterInvocationDefinitionMap extends AbstractFilterInvocationDefinitionSource{

	private static final Logger LOG = Logger.getLogger(RMSDBFilterInvocationDefinitionMap.class);
	private UIModuleLinkupBusinessService  uimodulelinkupBusinessService;

	
	@SuppressWarnings("rawtypes")
	@Override
	public Iterator getConfigAttributeDefinitions() {
		// TODO : Auto-generated method stub
		return null;
	}
	private UIModuleLinkupBusinessService getBusinessService()
	{
		if( null == uimodulelinkupBusinessService)
			setBusinessService((UIModuleLinkupBusinessService)ServiceLocator.getServiceLocator().locate("uimodulelinkupBusinessService"));
		return uimodulelinkupBusinessService;
	}
	public void setBusinessService(UIModuleLinkupBusinessService service){
		this.uimodulelinkupBusinessService = service;
	}
  
	private String trimUrl(String s)
	{
	   if(null !=s && s.contains("?"))
	   {
		   return s.substring(0,s.indexOf('?'));
	   }
		return s;
	}

	@Override
	public ConfigAttributeDefinition lookupAttributes(String url) {
		LOG.debug("inside lookupAttributes.");
		ConfigAttributeDefinition configAttr = null;
		try{
			// for login page we need to bypass this functionality.
			if(null ==url ||  url.startsWith("/login.htm"))
				return null;
			
			// for non .htm pages like images & css js files we need to bypass this functionality.
			if(!url.contains(".htm"))
				return null;
			
			List<String> roleNamesList = getBusinessService().findRolesByScreenName(trimUrl(url));
			//Set uniqueroleNamesSet = new HashSet(roleNamesList);   
			if (null!= roleNamesList && roleNamesList.size() != 0)
			{
				// TODO : Refactor this to use a cache instead.
				configAttr = new ConfigAttributeDefinition();
				Iterator<String> it = roleNamesList.iterator();
				while (it.hasNext()) {
					String s = (String) it.next();
					configAttr.addConfigAttribute(new SecurityConfig(s));
				}
			}
		
			//For .htm pages which are not attached to any module, "ROLE_CODESUPPORT" role should be set. As this is the minimal authority to access the system.
			if(null== configAttr)
			{
				 configAttr = new ConfigAttributeDefinition();
				 configAttr.addConfigAttribute(new SecurityConfig("ROLE_CODESUPPORT"));
			}
			return configAttr;

		}catch(Exception e){
			ExceptionFactory.createRMSException(LOG, e.getCause());
			LOG.error(e.getMessage());
			return null;
		}
	}
}